package com.brave.service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;

import com.brave.client.QywechatClient;
import com.brave.client.dto.AccessTokenDTO;
import com.brave.config.CorporationBaseInfo;
import com.brave.infrastructure.dao.TokenDAO;
import com.brave.infrastructure.dao.po.TokenPO;
import com.brave.infrastructure.dao.util.TokenStatus;
import com.brave.service.util.WXTokenType;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class TokenService {

	@Autowired
	QywechatClient qywechatClient;

	@Autowired
	CorporationBaseInfo corporationBaseInfo;

	@Autowired
	TokenDAO tokenDAO;

	public static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	/**
	 * 获取联系人token
	 * @return
	 */
	public String contactToken() {
		String contactSecret = corporationBaseInfo.getSecret().getContact();
		String compid = corporationBaseInfo.getCompid();
		AccessTokenDTO tokenDTO = qywechatClient.getContactToken(compid,contactSecret);
		if(null != tokenDTO) {
			//组装po实体
			TokenPO tokenPO = new TokenPO();
			tokenPO.setAccessToken(tokenDTO.getAccess_token());
			tokenPO.setExpiresIn(tokenDTO.getExpires_in());
			LocalDateTime createTime = LocalDateTime.now();
			tokenPO.setCreateTime(dateTimeFormatter.format(createTime));
			tokenPO.setStatus(TokenStatus.AVALI);
			tokenPO.setType(WXTokenType.CONTACT);
			//存储token到db
			tokenDAO.saveToken(tokenPO);

			return tokenDTO.getAccess_token();
		}
		return null;
	}

	/**
	 * 获取本地存储的Token有效的唯一
	 * @return String
	 */
	public String getTokenLocal(String tokenType) {
		List<TokenPO> tokenPOS = tokenDAO.getToken(tokenType);
		String result = null;
		if(null == tokenPOS || tokenPOS.size() < 1) {
			result =  null;
		}else{
			for (TokenPO tokenPO : tokenPOS) {
				int expireIn = tokenPO.getExpiresIn();
				String createTime = tokenPO.getCreateTime();
				LocalDateTime c = LocalDateTime.parse(createTime,dateTimeFormatter);
				long b = ChronoUnit.HOURS.between(c, LocalDateTime.now());
				long h = expireIn/3600;
				if(b<=h) {
					result =  tokenPO.getAccessToken();
					break;
				}else {
					tokenDAO.expireToken(tokenPO.getAccessToken());
				}
			}
		}
		if(null == result ) {
			return contactToken();
		}else {
			return result;
		}
	}


}
